package com.yuxi.al.sort;

/**
 * Created by yuxi on 17/2/5.
 */
public class InsertSort {
    public static void main(String[] args) {
        //插入排序
        int[] arr = {2, 3, 1, 33, 2, 4, 56, 42, 3, 21, 6, 7, 5};
        insertSort(arr);
        //排序后
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }

    private static void insertSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int tmp = arr[i];
            int j;
            //必须注意大于等于0这个边界条件
            for (j = i - 1; j >=0; j--) {
                if (arr[j] > tmp) {
                    arr[j + 1] = arr[j];
                } else {
                    break;
                }
            }
            arr[j + 1] = tmp;
        }
    }
}
